﻿using System;
using System.Linq;
using System.Security.Claims;
using ESoft.Core.Data.Service;
using ESoft.Core.Util.Helpers;
using ESoft.Core.Utils.Extensions;
using ESoft.Core.Web.VO;
using ESoft.Portal.Data.Domain;
using ESoft.Portal.Data.Domain.Entity;

namespace ESoft.Portal.Data.Service.Impl
{
    public class LoginService : ILoginService
    {
        private readonly IBaseService _baseService;
        public LoginService(IBaseService baseService)
        {
            this._baseService = baseService;
        }

        public User Login(string userName, string userPassword)
        {
            var user = this._baseService.QueryEntities<UUserEntity>(x => x.UserName.Equals(userName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            if (user == null)
            {
                throw new Exception("当前用户名不存在！");
            }
            if (!user.UserPassword.Equals(PasswordHelper.EncryptPassword(userPassword, user.Salt)))
            {
                throw new Exception("当前用户密码错误！");
            }

            User session = new User
            {
                UserId = user.UserId,
                UserName = user.UserName,
                UserType = user.UserType,
                ShopId = user.OrgId
            };

            return session;
        }

        public bool ValidateLastChanged(ClaimsPrincipal userPrincipal, string lastChanged)
        {
            return true;
        }
    }
}
